//
//  KKUtils.m
//  KKUtils
//
//  Created by jay Win on 2019/10/16.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "KKUtils.h"
#import "KKUtilsCommon.h"
#import <KKAnalytics.h>

#define FEEDBACK_DEVICE_INFO_FORMAT @"<br /><br /><br /><br /><font color=\"#9F9F9F\" style=\"font-size: 13px;\"> <i>(%@ %@ on %@ running with iOS %@</i>)</font>"

@interface KKUtils ()<MFMailComposeViewControllerDelegate>

@property(nonatomic, strong, nullable)NSString* localAssetID;

@end

@implementation KKUtils

+ (instancetype)shareUtils{
    static KKUtils* utils = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        utils = [[KKUtils alloc] init];
    });
    return utils;
}

- (void)vibrator:(int)type {
    if(@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleLight];
        if(type==1)
        {
            feedBackGenertor = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleMedium];
        }
        else
        {
            feedBackGenertor = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleHeavy];
        }
        [feedBackGenertor prepare];
        [feedBackGenertor impactOccurred];
    } else {
        AudioServicesPlaySystemSound(1519);
    }
}

#pragma mark - 邮件相关
- (void)sendEmail:(UIViewController *)rootViewController emailAddress:(NSString *)recipients title:(NSString *)subject productName:(NSString *)disPlayName{
    NSString* mailSource = @"application";
    if([MFMailComposeViewController canSendMail]){
        NSString *appVersion = [NSString stringWithFormat:@"%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]];
        NSString *deviceInfo = [NSString stringWithFormat:FEEDBACK_DEVICE_INFO_FORMAT, disPlayName, appVersion, [UIDevice currentDevice].model,[UIDevice currentDevice].systemVersion];
        MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc]init];
        mailComposeViewController.mailComposeDelegate = self;
        NSString* title = [@"iOS " stringByAppendingString:NSLocalizedString(@"App.Name" , nil)];
        [mailComposeViewController setSubject:title];
        [mailComposeViewController setToRecipients:@[recipients]];
        [mailComposeViewController setMessageBody:deviceInfo isHTML:YES];
        mailComposeViewController.modalPresentationStyle = UIModalPresentationPageSheet;
        mailComposeViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [rootViewController presentViewController:mailComposeViewController animated:YES completion:^{}];
    } else {
        mailSource = @"safari";
        if(recipients==nil){
            recipients=@"mailto:subject=feedback@picfuntech.com";
        }
//        NSString *body = @"&body=";
        if (![recipients containsString:@"mailto:"]) {
            recipients = [NSString stringWithFormat:@"mailto:%@", recipients];
        }
//        NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
        NSString* email = [recipients stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
    }
    [[KKAnalytics shareManager] logTKEvent:@"KK_SEND_MAIL_ACTION" params:@{@"send_way":mailSource, @"recipients": recipients, @"title": subject, @"product_name": disPlayName}];
}

#pragma mark - MFMailComposeViewControllerDelegate
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [controller dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - 系统功能相关
- (void)showCommentDialog{
    if(@available(iOS 10.3, *)) {
        [SKStoreReviewController requestReview];
    } else {
        KKUtilsLog(@"不受支持的支持系统版本");
    }
}

- (void)copyStringToClipboard:(NSString *)content{
     UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
    [pasteBoard setString:content];
}

- (BOOL)hasInstallApp:(NSString *)urlSchemes{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlSchemes]]){
        return  YES;
    } else {
        return  NO;
    };
}

#pragma mark - 权限相关
- (BOOL)checkCameraPermission{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        return NO;
    } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        return NO;
    } else {
        return YES;
    }
#else
    KKUtilsLog(@"__IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_7_0");
    return NO;
#endif
}

- (BOOL)checkAlbumPermission{
    BOOL isAlbumAuthor = NO;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    isAlbumAuthor = YES;
    if (authStatus == PHAuthorizationStatusRestricted || authStatus == PHAuthorizationStatusDenied) {
        isAlbumAuthor = NO;
    }
#else
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    isAlbumAuthor = YES;
    if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied) {
        isAlbumAuthor = NO;
    }
#endif
    return isAlbumAuthor = NO;;
}

- (void)requestCameraPermission:(KKPermissionRequestCompletionHandler)handler {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        handler(granted);
    }];
}
- (void)requestAlbumPermission:(KKPermissionRequestCompletionHandler)handler {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            handler(YES);
        } else {
            handler(NO);
        }
    }];
}

#pragma makr - iPhone 本地分享
- (void)shareNative:(UIViewController *)rootViewController filePath:(NSString *)url{
    NSURL *fileURL = [NSURL fileURLWithPath:url];
    if (!fileURL) {
        KKUtilsLog(@"file not exsits. please check filepath.");
        return;
    }
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        UIPopoverController *popoverController = [[UIPopoverController alloc]initWithContentViewController:[[UIActivityViewController alloc] initWithActivityItems:@[fileURL] applicationActivities:nil]];
        CGRect rect = CGRectMake(10, 100, 200, 200);
        [popoverController presentPopoverFromRect:rect inView:rootViewController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    } else {
        [rootViewController presentViewController:[[UIActivityViewController alloc] initWithActivityItems:@[fileURL] applicationActivities:nil] animated:YES completion:nil];
    }
}

#pragma mark - 保存到相册
- (void)saveToAlbum:(NSString *)filePath complete:(KKAssetCompletionHandler)handler{
    NSURL* fileURL = [NSURL fileURLWithPath:filePath];
    BOOL isVideo = NO;
    if ([filePath hasSuffix:@"mp4"]) {
        isVideo = YES;
    }
    if (!fileURL) {
        KKUtilsLog(@"file not exsits. please check filepath.");
        NSError* error = [NSError errorWithDomain:@"com.kksdk.utils" code:4002 userInfo:@{@"reason": @"save asset failed, please check filePath is correct."}];
        handler(NO, nil, error);
        return;
    }
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest* request;
        if (isVideo) {
            request = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:fileURL];
        } else {
            request = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:fileURL];
        }
        self.localAssetID = request.placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        handler(success, self.localAssetID, error);
    }];
}

- (void)shareToInstagram:(NSString *)filePath complete:(KKCompletionHandler)handler{
    [self saveToAlbum:filePath complete:^(BOOL isSuccess, NSString * _Nullable assetLocalID, NSError * _Nullable error) {
        if (!isSuccess || assetLocalID == nil) {
            [[KKAnalytics shareManager] logTKEvent:@"KK_SHARE_INS_ACTION" params:@{@"is_success":@"fail", @"url": @"null_url", @"reason": [NSString stringWithFormat:@"save_asset_failed:%@", filePath]}];
            handler(NO, error);
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([self hasInstallApp:KK_INS_SCHEMA]) {
                // 已安装APP
                NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@" =\"#%/:&<>?@\\^`{|}"];
                characterSet = [characterSet invertedSet];
                NSURL* url = [NSURL fileURLWithPath:filePath];
                NSString* escapedString   = [url.absoluteString stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
                NSString* caption = @"";
                NSString* escapedCaption = [caption stringByAddingPercentEncodingWithAllowedCharacters:characterSet];
                NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@", escapedString, escapedCaption]];
                [[UIApplication sharedApplication] openURL:instagramURL];
                [[KKAnalytics shareManager] logTKEvent:@"KK_SHARE_INS_ACTION" params:@{@"is_success":@"success", @"url": instagramURL, @"reason": @"null_reason"}];
                handler(YES, nil);
            } else {
                NSError* error = [NSError errorWithDomain:@"com.kksdk.utils" code:4001 userInfo:@{@"reason": @"instram is not install"}];
                [[KKAnalytics shareManager] logTKEvent:@"KK_SHARE_INS_ACTION" params:@{@"is_success":@"fail", @"reason": @"instram_is_not_install", @"url": @"null_url"}];
                handler(NO, error);
            }
        });
    }];
}

- (NSString *)getLanguage{
    return [[NSLocale preferredLanguages] objectAtIndex:0];
}

- (NSString *)getLocale{
    return [[NSLocale currentLocale]localeIdentifier];;
}

- (void)checkUpdateAppVersion:(NSString *)appStoreID title:(NSString *)titleText positive:(NSString *)positiveButtonText negative:(NSString *)negativeButtonText message:(NSString *)customMessage{
    
}

#pragma mark - 设备判断相关
-(BOOL)isIPad {
    return NO;
}

- (BOOL)isIphoneXAbove{
    return ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? (CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) || CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) || CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size)) : NO);
}
@end


extern "C"{

void Vibrator(int type){
    KKUtils *util = [KKUtils new];
    [util vibrator:type];
}

void SendEMail( const char* recipients, const char* subject,const char* productName){
    KKUtils *util = [KKUtils shareUtils];
    UIViewController* rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    [util sendEmail:rootViewController emailAddress:[NSString stringWithUTF8String:recipients] title:[NSString stringWithUTF8String:subject] productName:[NSString stringWithUTF8String:productName]];
}

void ShowSystemCommentDialog(){
    KKUtils *util = [KKUtils new];
    [util showCommentDialog];
}

void CopyStringToClipboard(char *content){
    KKUtils *util = [KKUtils new];
    [util copyStringToClipboard:[NSString stringWithUTF8String:content]];
}

bool HasInstallApp(char *urlSchemes){
    KKUtils *util = [KKUtils new];
    return [util hasInstallApp:[NSString stringWithUTF8String:urlSchemes]];
}

void ShareNative(char *path){
    KKUtils *util = [KKUtils new];
    UIViewController* rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    [util shareNative:rootViewController filePath:[NSString stringWithUTF8String:path]];
}

void SaveToAlbum(char *path){
    KKUtils *util = [KKUtils new];
    [util saveToAlbum:[NSString stringWithUTF8String:path] complete:^(BOOL isSuccess, NSString * _Nullable assetLocalID, NSError * _Nullable error) {
        
    }];
}

void ShareToInstagram(char *path){
    KKUtils *util = [KKUtils new];
    [util shareToInstagram:[NSString stringWithUTF8String:path] complete:^(BOOL isSuccess, NSError * _Nullable error) {
        
    }];
}

bool CheckCameraPermission(){
    KKUtils *util = [KKUtils new];
    return [util checkCameraPermission];
}

bool CheckAlbumPermission(){
    KKUtils *util = [KKUtils new];
    return [util checkAlbumPermission];
}

void RequestCameraPermission(){
    KKUtils *util = [KKUtils new];
    [util requestCameraPermission:^(BOOL hasPermisssion) {
        
    }];
}

void RequestAlbumPermission(){
    KKUtils *util = [KKUtils new];
    [util requestAlbumPermission:^(BOOL hasPermisssion) {
        
    }];
}

bool IsIphoneXAbove(){
    KKUtils *util = [KKUtils new];
    return [util isIphoneXAbove];
}


char *GetLanguage(){
    KKUtils *util = [KKUtils new];
    const char *result = [[util getLanguage] UTF8String];
    char* templateChar = (char *)malloc(strlen(result) + 1);
    return strcpy(templateChar, result);
}

char *GetLocale(){
    KKUtils *util = [KKUtils new];
    const char* result = [[util getLocale] UTF8String];
    char* templateChar = (char *)malloc(strlen(result) + 1);
    return strcpy(templateChar, result);
}

bool IsIPad(){
    KKUtils *util = [KKUtils new];
    return [util isIPad];
}

void PopupUpdateNoticeDialog(char *appStoreID,char *title,char *positiveText,char *cancelText,char *customMessage){
    NSString *messageText=@"";
    if(customMessage){
        messageText=[NSString stringWithUTF8String:customMessage];
    }
    KKUtils *util = [KKUtils new];
    [util checkUpdateAppVersion:[NSString stringWithUTF8String:appStoreID]
                          title:[NSString stringWithUTF8String:title]
                       positive:[NSString stringWithUTF8String:positiveText]
                       negative:[NSString stringWithUTF8String:cancelText]
                        message:messageText];
}
}
